﻿using EONFULLSIN.Models;
using EONFULLSIN.Models.Entity.User;
using EONFULLSIN.Models.Enum;
using EONFULLSIN.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using User = EONFULLSIN.Models.Entity.User.User;

namespace EONFULLSIN.Views.UserView
{
    public partial class UserAdd : UserControl
    {
        private Form _form;
        private long? selectId;
        private User update;

        public UserAdd(Form form, string formTitle, long? id = null)
        {
            _form = form;
            selectId = id;
            InitializeComponent();
            this.btn_sure.Click += Btn_sure_Click;
            this.btn_cancel.Click += Btn_cancel_Click;
            this.header_title.Text = formTitle;
            if (formTitle.Equals("编辑用户"))
            {
                update = EFDAL.Instance.GetModel<User>(x => x.Id.Equals(selectId));
                txt_user.Text = update.Name;
                txt_account.Text = update.Account;
                txt_pwd.Text = update.PassWord;
                select_role.SelectedIndex = (int)update.Rank;
            }
        }

        private void Btn_sure_Click(object sender, EventArgs e)
        {
            if (header_title.Text.Equals("新增用户"))
            {
                User user = new User();
                user.Name = txt_user.Text;
                user.Account = txt_account.Text;
                user.PassWord = txt_pwd.Text;

                user.Rank = (RoleTypeEnum)Enum.Parse(typeof(RoleTypeEnum), select_role.Text);
                user.Status = true;
                EFDAL.Instance.AddModel(user);
            }
            else
            {
                update.Name = txt_user.Text;
                update.Account = txt_account.Text;
                update.PassWord = txt_pwd.Text;
                update.Rank = (RoleTypeEnum)Enum.Parse(typeof(RoleTypeEnum), select_role.Text);
                EFDAL.Instance.UpdateModel<User>(x => x.Id.Equals(update.Id), x => new User() { Name = update.Name, Account = update.Account, PassWord = update.PassWord, Rank = update.Rank });
            }
            this.Dispose();
        }

        private void Btn_cancel_Click(object sender, EventArgs e)
        {
            this.Dispose(true);
        }
    }
}